package com.jaws.core.mvc.view;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;

import lombok.Data;

import org.springframework.context.ApplicationContext;
import org.springframework.core.Ordered;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;

/**
 * 视图解析器
 * @author maojian
 * @date 2018-05-21 15:54:11
 * @since v1.0.0
 */
@Data
public class JawsViewResolver implements ViewResolver, Ordered{
	
	@Resource
	private ApplicationContext context;
	
	private Map<String,View> viewMap = new HashMap<String,View>();
	
	@PostConstruct
	private void init(){
		Map<String,JawsAbstractView> beanMap = context.getBeansOfType(JawsAbstractView.class);
		if(null == beanMap){
			return ;
		}
		for(String key : beanMap.keySet()){
			JawsAbstractView jawsAbstractView = beanMap.get(key);
			viewMap.put(jawsAbstractView.getView(), jawsAbstractView);
		}
	}
	
	@Override
	public View resolveViewName(String viewName, Locale locale) throws Exception {
		return viewMap.get(viewName);
	}

	@Override
	public int getOrder() {
		return Ordered.HIGHEST_PRECEDENCE;
	}
	
	public void addView(String viewName, View view){
		viewMap.put(viewName, view);
	}
	
	public void removeView(String viewName){
		viewMap.remove(viewName);
	}

}
